<?php
namespace Home\Controller;

use Utuo\MallForeground;
use My\Model\MallOrderModel;
use Utuo\Region;
use My\Model\WechatUserModel;
use My\Model\MallRedPacketModel;
use My\Model\MallJobTitleModel;
use My\Model\UserRole;

class MallController extends MallForeground { 
	
	/**
	 * 初始化
	 */
	public function _init() {
		layout('Mall/layout');
		$this->setModelName('Mall');
		$this->setModelControllerName(); 
		if ( !in_array(ACTION_NAME, array('downCust','addBank','getCityPost','saveBank','withdrawPost','bankList','setDefaultBank','materialList')) ) { // 排除不支持分享跳转的链接
			$this->setSupportRedirect(isset($_REQUEST['debug']) ? false : true);
		}
	}
	
	/**
	 * 首页
	 */
	public function indexAction() {
		$this->setPageTitle($this->config['name']);
		$goodsLists = $this->goodsLists();
		$mallPage = M("MallPage")->where(array('cid'=>$this->cid))->field("id,icon,name")->select();
		$this->assign('mallPage', $mallPage);
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 * 金牌会员商品
	 */
	public function dealerIndexAction() {
		$this->setPageTitle($this->config['name']);
		$goodsLists = $this->dealerGoodsLists();
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 * 扩展信息
	 */
	public function pageAction() {
		$id = I('id', 0, 'intval');
		$config = M('MallPage')->where("cid=%d AND id=%d", $this->sid, $id)->find();
		$this->assign('mallPage', $config);
		$this->display();
	}
	
	/**
	 * 获得金牌会员商品
	 */
	public function dealerGoodsLists() {
		$userRole = new UserRole();
		if ( $userRole->type($this->user['type'])->isNot(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
			header('Content-Type:text/html; charset=utf-8');
			$this->redirect('Mall/index', array('sid'=>$this->cid), 5, "您还不是金牌会员无权查看金牌会员商品");
		}
		$goodsLists = M("MallGoods")->where(array('cid'=>$this->cid, 'is_deleted' => 0, 'status' => 1, 'dealer_price'=>array("gt", 0)))->order('sort asc,id desc')->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['attrs_cfg'] = unserialize($v['attrs_cfg']);
			$v['images'] = unserialize($v['images']);
			$v['url'] = U("Mall/show", array('sid' => $this->cid, 'id' => $v['id'], 'mid' => $this->user['id'] ));
		}
		return $goodsLists;
	}
	
	/**
	 * 获得分销商品
	 */
	public function goodsLists() {
		$goodsLists = M("MallGoods")->where(array('cid'=>$this->cid, 'is_deleted' => 0, 'status' => 1))->order('sort asc,id desc')->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['attrs_cfg'] = unserialize($v['attrs_cfg']);
			$v['images'] = unserialize($v['images']);
			$v['url'] = U("Mall/show", array('sid' => $this->cid, 'id' => $v['id'], 'mid' => $this->user['id'] ));
		}
		return $goodsLists;
	}
	
	/**
	 * 商品详细
	 */
	public function showAction() {
		$id = I('id', 0, "intval");
		$goods = M("MallGoods")->where("cid=%d and id=%d", $this->cid, $id)->find();
		if ( $goods ) {
			if ( $goods['try'] ) {
				redirect(U('MallTry/show', "goodsId={$goods['id']}&sid={$this->sid}"));	
			}
			
			$goods['attrs_cfg'] = unserialize($goods['attrs_cfg']);
			$goods['images'] = unserialize($goods['images']);
			
			$this->setShare(array(
					'desc' => $goods['description'],
					'title' => $goods['name'],
			));
			
			$this->setPageTitle($goods['name']);
			$this->assign("shopGoods", $goods);
			$this->display();
		} else {
			$this->error('商品已不存在');
		}
	}
	
	/**
	 * 个人中心
	 */
	public function myAction() {
		$this->setPageTitle('用户中心');
		// 订单导航
		$this->getOrderNav();
		// 礼单导航
		$this->getGiftsNav();
		// 红包导航
		$this->getRedPacketNav();
		// 用户信息
		$user = $this->getUser();
		$this->assign("user", $user);
		$this->assign("backUrl", urlencode($this->getCurrentUrl()));
		$this->display();
	}
	
	/**
	 * 我的业绩
	 */
	public function achievementAction() {
		$this->setPageTitle("我的业绩");
		$goodsLists = M("MallGoodsPromotion a")->join("__MALL_GOODS__ b on a.productId = b.id", "LEFT")
													->where(array(
														'a.cid' => $this->cid,
														'a.uid' => $this->uid,
													))
													->field("a.orderCount,a.saledTotal,a.rewardsTotal,a.dealerRewardsTotal,b.name,b.price,b.images,b.id,b.reward_set,b.reward_price,b.reward_percent,b.reward_set_dealer,b.reward_price_dealer,b.reward_percent_dealer")
													->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['imageFirst'] = array_shift(unserialize($v['images']));
			$v['myBouns'] = $this->getRewardPercent( $v );
		}
		$this->assign("unpromotionCount", $this->getUnpromotionCount());
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 *  获得未推广的商品数
	 */
	private function getUnpromotionCount() {
		$sharedProductIdSql = M("MallGoodsPromotion")->where('cid=%d and uid=%d', $this->cid, $this->uid)->field('productId')->select(false);
		$condition = array(
				'cid' => $this->cid,
				'id' => array('exp', "not in $sharedProductIdSql"),
				'status' => 1,
				'is_deleted' => 0,
		);
		return M("MallGoods")->where($condition)->count();
	}
	
	/**
	 * 有佣金显示的商品列表
	 */
	public function shareGoodsAction() {
		$exceptShared = I('exc', 0); // 排除已分享过的商品
		$condition = array(
			'cid' => $this->cid,
			'status' => 1,
			'is_deleted' => 0,
		);
		$sharedProductIdSql = M("MallGoodsPromotion")->where('cid=%d', $this->cid)->field('productId')->select(false);
		$exceptShared and $condition['id'] = array('exp', "not in $sharedProductIdSql");
		$goodsLists = M("MallGoods")->where($condition)->select();
		foreach ( $goodsLists as $k => &$v ) {
			$v['imageFirst'] = array_shift(unserialize($v['images']));
			$v['myBouns'] = $this->getRewardPercent( $v );
		}
		$this->assign("goodsLists", $goodsLists);
		$this->display();
	}
	
	/**
	 * 素材列表
	 */
	public function materialListAction() {
		$id = I('id', 0, 'intval');
		$mallMaterialLists = M("MallGoodsMaterial")->where('cid=%d and productId=%d and status=1 and is_deleted=0', $this->cid, $id)->select();
		foreach ( $mallMaterialLists as &$v) {
			$v['url'] = U('Mall/showMaterial', 'sid='.$this->sid."&id=".$v['id']);
		}
		$mallMaterialLists or $mallMaterialLists = array();
		$mallMaterialLists[] = array('name' => '产品详细',
												'url' => U('Mall/show', 'sid='.$this->sid."&id=".$id));
		$this->ajaxSuccess('', $mallMaterialLists);
	}
	
	/**
	 * 显示素材信息
	 */
	public function showMaterialAction() {
		$id = I('id', 0, 'intval'); // 素材id
		$mallGoodsMaterial = M("MallGoodsMaterial a")->join('__MALL_GOODS__ b on a.productId=b.id')
																			->where('a.cid=%d and a.id=%d', $this->cid, $id)
																			->field('a.*')->find();
		$mallGoodsMaterial['url'] = U('Mall/show', "sid={$this->sid}&id={$mallGoodsMaterial['productId']}");
		$this->setPageTitle($mallGoodsMaterial['title']);
		$this->assign("mallGoodsMaterial", $mallGoodsMaterial);
		$this->setShare(array(
			'desc' => $mallGoodsMaterial['description'],
			'title' => $mallGoodsMaterial['title'],
		));
		$this->display();	
	}
	
	/**
	 * 我的下线客户
	 */
	public function myCustAction() {
		$userList = M("WechatUser")->where(array('mid'=>$this->uid))->field('*,1 as level')->select();
		$this->assign("userList", $userList);
		$this->display();
	}
	
	/**
	 * 下线客户异步请求
	 */
	public function downCustAction() {
		$mid = I('fid', $this->uid, 'intval');
		$wechatUserList = M("WechatUser a")->join("__MALL_USER_TREE__ b on a.id=b.uid")->where(array('a.mid' => $mid, 'a.cid' => $this->cid))->field('a.*,b.tree')->select();
		foreach ( $wechatUserList as &$v) {
			$v['level'] = $this->getLevel($this->uid, $v['tree']);
		}
		$this->ajaxSuccess('', $wechatUserList);
	}
	
	/**
	 * 我的分销订单
	 */
	public function disOrderAction() {
		$orderLists = M("MallOrder a")->join("__WECHAT_USER__ b on a.uid=b.id", "LEFT")
							  ->join("__MALL_USER_TREE__ c on c.uid=b.id", "LEFT")
							  ->field("a.*,b.nickname,c.tree")
							  ->where(array(
							  		'a.order_status' => MallOrderModel::ORDER_STATUS_COMPLETED,
									'a.reward_uids'=>array('exp', "!='' and a.reward_uids is not null and find_in_set('{$this->uid}', a.reward_uids)") // 在参与返佣的用户之内
								))->select();
		foreach ( $orderLists as &$v ) {
			$v['all_rewards'] = array_combine(explode(',', $v['reward_uids']), explode(',', $v['reward_bonus']));
			$v['my_rewards'] = $v['all_rewards'][$this->uid];
			$v['level'] = $this->getLevel($this->uid, $v['tree']);
		}
		$this->assign("orderLists", $orderLists);
		$this->display();
	}
	
	/**
	 * 我的奖金(积分)
	 */
	public function myBonusAction() {
		$user = $this->getUser();
		$this->assign("user", $user);
		$this->display();
	}
	
	/**
	 * 提现页
	 */
	public function withdrawAction() {
		$this->setPageTitle("提现申请");
		$user = $this->getUser();
		$defaultBank = $this->getDefaultBank();
		$user['defaultBank'] = $defaultBank;
		$this->assign("backUrl", urlencode($this->getCurrentUrl()));
		$this->assign("user", $user);
		$this->display();
	}
	
	/**
	 * 提现记录
	 */
	public function withdrawRecordAction() {
		$withdrawRecord = M("MallUserWithdraw")->where("cid=%d and uid=%d", $this->cid, $this->uid)->order('createTime desc')->select();
		$this->assign("withdrawRecord", $withdrawRecord);
		$this->display();
	}
	
	/**
	 * 提现提交
	 */
	public function withdrawPostAction() {
		function getmicrotime($e = 7) {
			list($u, $s) = explode(' ',microtime());
			return bcadd($u, $s, $e);
		}
		// 默认支付银行
		$defaultUserBankId = I("defaultUserBankId", 0, "intval");
		$mallUserBank = M("MallUserBank a")->join("__BANK__ b on a.bankId=b.id", "LEFT")->where("a.id=%d", $defaultUserBankId)->field("a.*,b.name as bankName")->find();
		if ( empty($mallUserBank) ) {
			$this->ajaxError('未选择支付的银行');
		}
		// 记录提现
		$no = str_replace('.', '', getmicrotime()).rand(100, 999).$this->uid ;
		$m = M("MallUserWithdraw");
		if ( $m->create() ) {
			$m->cid = $this->cid;
			$m->uid = $this->uid;
			$m->status = 0;
			$m->createTime = time();
			$m->no = $no;
			$m->bankName = $mallUserBank['bankName'];
			$m->accountName = $mallUserBank['accountName'];
			$m->account = $mallUserBank['account'];
			$user = $this->getUser();
			if ( $user['withdrawable']*1 and $user['withdrawable']*1 >= $m->money  ) {
				if ( $m->add() ) {
					$this->ajaxSuccess('提现申请成功');
				} else {
					$this->ajaxError('提现申请失败');
				}
			} else {
				$this->ajaxError('输入的积分超出了可提积分');
			}
		}
		$this->ajaxError($m->getError());
	}
	
	/**
	 * 添加收款银行
	 */
	public function addBankAction() {
		C("TOKEN_ON", false);
		$bank = array();
		$banks = M("Bank")->getField('id,name');
		$bank['provinceOptions'] = $this->getOption(Region::getProvinceList(), $bank['province'], '==请选择省份==');
		$bank['cityOptions'] = $this->getOption(Region::getCityListByProvince($bank['province']), $bank['city'], '==请选择城市==');
		$bank['bankOptions'] = $this->getOption($banks);
		$this->assign("bank", $bank);
		$this->assign("backUrl", urldecode(htmlspecialchars_decode(I('request.back'))));
		$this->display("saveBank");
	}
	
	/**
	 * 保存收款银行
	 */
	public function modifyBankAction() {
		C("TOKEN_ON", false);
		$id = I('id', 0, 'intval');
		$m = M("MallUserBank");
		$bank = $m->where('id=%d and uid=%d', $id, $this->uid)->find();
		$banks = M("Bank")->getField('id,name');
		$bank['provinceOptions'] = $this->getOption(Region::getProvinceList(), $bank['province'], '==请选择省份==');
		$bank['cityOptions'] = $this->getOption(Region::getCityListByProvince($bank['province']), $bank['city'], '==请选择城市==');
		$bank['bankOptions'] = $this->getOption($banks);
		$this->assign("bank", $bank);
		$this->assign("backUrl", urldecode(htmlspecialchars_decode(I('request.back'))));
		$this->display("saveBank");
	}
	
	/**
	 * 银行列表
	 */
	public function myBankListAction() {
		$bankLists = M("MallUserBank a")->join("__BANK__ b on a.bankId=b.id", "LEFT")->where("a.cid=%d and a.uid=%d", $this->cid, $this->uid)
												->field("a.*,b.name as bankName")->order('isDefault desc')->select();
		foreach ($bankLists as &$v) {
			$v['lastCode'] = substr($v['account'], -4);
		}
		$this->assign("bankLists", $bankLists);
		$this->assign("backUrl", urldecode(htmlspecialchars_decode(I('request.back'))));
		$this->display();
	}
	
	/**
	 * 保存银行
	 */
	public function saveBankAction() {
		C("TOKEN_ON", false);
		$m = M("MallUserBank");
		if ( $m->create() ) {
			$m->cid = $this->cid;
			$m->uid = $this->uid;
			if ( empty($m->id) ) {
				unset($m->id);
				$m->isDefault = 1;
				$id = $m->add();
				if ( $id ) {
					$m->where(array('id' => array('neq', $id), 'uid' => $this->uid))->setField("isDefault", 0);
					$this->ajaxSuccess("添加成功");
				} else {
					$this->ajaxSuccess("添加失败");
				}
			} else {
				if ( false !== $m->where('id=%d', $this->id)->save() ) {
					$this->ajaxSuccess("修改成功");
				} else {
					$this->ajaxError("修改失败");
				}
			}
		}
		$this->ajaxError($m->getError());
	}
	
	/**
	 * 获取城市
	 */
	public function getCityPostAction() {
		echo $this->getOption(Region::getCityListByProvince(I('code')), '', '==请选择城市==');
	}
	
	/**
	 * 设置默认银行
	 */
	public function setDefaultBankAction() {
		$id = I('bankId', 0, "intval");
		$m = M("MallUserBank");
		if ( false !== $m->where(array('uid' => $this->uid))->save(array('isDefault' => array('exp', "CASE id WHEN $id THEN 1 ELSE 0 END"))) ) {
			$this->ajaxSuccess('设置成功');
		} else {
			$this->ajaxSuccess('设置失败');
		}
	}
	
	/**
	 * 获得用户级别
	 * @param unknown $id 根级id
	 * @param unknown $tree tree字符串
	 * @return number
	 */
	private function getLevel($id, $tree) {
		$i = 0;
		$treeAttr = explode(',', $tree);
		foreach ( $treeAttr as $v ) {
			if ( $v != $id ) {
				$i++;
			} else {
				break;
			}
		}
		return $i;
	}
	
	/**
	 * 获得默认银行
	 * @return string
	 */
	private function getDefaultBank() {
		$userBank = M("MallUserBank a")->where(array(
			'a.cid' => $this->cid,
			'a.uid' => $this->uid,
		))->join("__BANK__ b on a.bankId=b.id", "LEFT")->field("a.*,b.name as bankName")->order('a.isDefault desc')->limit(1)->find();
		$userBank and $userBank['lastCode'] = substr($userBank['account'], -4);
		return $userBank;
	}
	
	/**
	 * 获得用户提现信息
	 * @return Ambigous <number, string>
	 */
	private function getUser() {
		// 用户信息
		$user = M("WechatUser")->find($this->uid);
		// 可提现
		$money = M("MallUserWithdraw")->where("uid=%d and status=0", $this->uid)->sum('money'); // 授理中的提现
		$minWithdraw = $this->config['min_withdraw'];
		$withdrawable = $user['bonus']*1 - $user['mention']*1 - $money; // 可提
		if ( $withdrawable < $minWithdraw ) {
			$user['withdrawable'] = '0.00';
		} else {
			$user['withdrawable'] = number_format($withdrawable, 2);
		}
		$user["typeName"] = WechatUserModel::getUserTypeName($user['type'], $this->cid, $user['id']);
		$jogTitle = MallJobTitleModel::getJobTitleList( $this->cid );
		$user['engagedInMoney'] = $money;
		return $user;
	}
	
	/**
	 * 送礼导航
	 */
	private function getGiftsNav() {
		$types = array();
		foreach (MallOrderModel::$GIFTS_TYPES as $type => $v) {
			$condition = array(
					"orders.uid" => $this->uid,
					"orders.cid" => $this->sid,
					"orders.buy_method" => MallOrderModel::BUY_METHOD_GIFTS,
			);
			if ( $type == 1 ) { // 我的送礼 
				
			} elseif( $type == 2 ) { // 我的收礼
				unset($condition['orders.uid']);
				$condition['gifts.to_uid'] = $this->uid;
			}
			$count = M("MallOrder orders")->join ( "__MALL_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" )->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("giftsTypes", $types);
	}
	
	/**
	 * 红包导航
	 */
	private function getRedPacketNav() {
		$types = array();
		foreach (MallRedPacketModel::$EFFICACYS_NAV as $type => $v) {
			$condition = array(
					"packet.uid" => $this->uid,
					"packet.cid" => $this->sid,
					"packet.efficacy" => $type,
					"packet.endTime" => array('exp', "=0 or packet.endTime>unix_timestamp()"),
			);
			$count = M("MallRedPacket packet")->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("redPacketTypes", $types);
	}
	
	/**
	 * 订单导航
	 */
	private function getOrderNav() {
		$types = array();
		foreach (MallOrderModel::$TYPES as $type => $v) {
			$d = M("MallOrder orders");
			$condition = array(
					"orders.uid" => $this->uid,
					"orders.cid" => $this->sid
			);
			if ($type == 1) { // 未付款
				$condition['orders.order_status'] = MallOrderModel::ORDER_STATUS_PAY;
			} else if ($type == 2) { // 待签收(已付款,货到付款)
				$condition['orders.order_status'] = array(
						"in",
						array(
								MallOrderModel::ORDER_STATUS_SHIPPING,
								MallOrderModel::ORDER_STATUS_SIGN
						)
				);
				unset( $condition['orders.uid'] ); 
				/* 我的待收货订单与 收礼订单 */
				$d->join ( "__MALL_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" );
				$condition['orders.id'] = array('exp', "is not null and (
													((gifts.to_uid=0 or gifts.to_uid is null) and orders.uid={$this->uid}) 
														or 
													(gifts.to_uid={$this->uid})
												)");
			} else if ($type == 3) { // 交易成功
				$condition['orders.order_status'] = MallOrderModel::ORDER_STATUS_COMPLETED;
			} else if ($type == 4) { // 退款订单
				$condition['orders.refund_times'] = array('gt', 0);
			} else { // 其它
				$condition['orders.order_status'] = array(
						"not in",
						array(
								MallOrderModel::ORDER_STATUS_PAY,
								MallOrderModel::ORDER_STATUS_SHIPPING,
								MallOrderModel::ORDER_STATUS_SIGN,
								MallOrderModel::ORDER_STATUS_COMPLETED
						)
				);
			}
			$count = $d->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("types", $types);
	}
	
	private function getRewardPercent( $shopGoods ) {
		/* 基础分成比例 */
		$rewardPrice = $shopGoods['reward_price']; // 特约经销商佣金
		$rewardPercent = array();
		$bonus = array();
		if ( $shopGoods['reward_set'] ) { // 商品设置的分成比例
			$shopGoods['reward_percent'] and $rewardPercent = explode(':', $shopGoods['reward_percent']);
		} else { // 系统默认分成比例
			$this->config['reward_percent'] and $rewardPercent = explode(':', $this->config['reward_percent']);
		}
		foreach ( $rewardPercent as $v ) {
			$bonus[] = $v/100*$rewardPrice."(基础)";
		}
			
		if ( $this->user['type'] == WechatUserModel::USER_TYPE_FRANCHISED_DEALER ) {
			/* 特约经销商佣金发放比例 */
			$rewardPriceDealer = $shopGoods['reward_price_dealer']; // 特约经销商佣金
			$rewardPercentDealer = array();
			/* 特约经销商分成比例  */
			if ( $shopGoods['reward_set_dealer'] ) { // 商品设置的分成比例
				$shopGoods['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $shopGoods['reward_percent_dealer']);
			} else { // 系统默认分成比例
				$this->config['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $this->config['reward_percent_dealer']);
			}
			$i = 0;
			foreach ( $rewardPercentDealer as $v ) {
				$bonus[$i] = $bonus[$i].($bonus[$i]?"+":"").'￥'.($v/100*$rewardPriceDealer)."(特销商)";
				$i++;
			}
		}
		return $bonus[0]?$bonus[0]:'无佣金';
	}
}